package com.dp.mallchat.common.common.inteceptor;

import com.dp.mallchat.common.common.domain.enums.HttpErrorEnum;
import com.dp.mallchat.common.user.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.Optional;

/**
 * @Author: dupeng
 * @CreateTime: 2024-06-03  10:52
 * @Description: token拦截器
 */
@Order(1)
@Component
public class TokenInterceptor implements HandlerInterceptor {

    public static final String TOKEN_AUTHORIZATION = "Authorization";
    public static final String TOKEN_AUTHORIZATION_BEARER = "Bearer ";
    public static final String ATTRIBUTE_UID = "uid";

    @Autowired
    private LoginService loginService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = getToken(request);
        Long uid = loginService.getValidUid(token);
        if (Objects.nonNull(uid)) {    //登录态
            request.setAttribute(ATTRIBUTE_UID, uid);
        } else {
            boolean isPublicUrl = isPublicUrl(request.getRequestURI());
            if (!isPublicUrl) { //又没有登录态，又不是公开路径，直接401
                HttpErrorEnum.ACCESS_DENIED.sendHttpError(response);
                return false;
            }
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    private String getToken(HttpServletRequest request) {
        return Optional.ofNullable(request)
                .map(map -> map.getHeader(TOKEN_AUTHORIZATION))
                .filter(h -> h.startsWith(TOKEN_AUTHORIZATION_BEARER))
                .map(t -> t.replace(TOKEN_AUTHORIZATION_BEARER, ""))
                .orElse(null);
    }

    private boolean isPublicUrl(String url) {
        String[] split = url.split("/");
        return split.length > 3 && "public".equals(split[3]);
    }
}
